﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Xml;
using System.Xml.Linq;
using System.ServiceModel.Syndication;
using PBDesk.com.Extension.FeedsAggregator;
using PBDesk.Utilities;
using System.IO;

namespace PBDesk.com.Extension.UmbHelper
{
    public class AdminTasks
    {
        public static void WriteTWC9File()
        {
            MyLog.Write<AdminTasks>("AdminTasks::WriteTWC9File()", "Method Call Start");
            try
            {
                string fileName = MyUmb.CacheFilesLoc + "TWC9.xml";
                XmlTextWriter t = new XmlTextWriter(fileName, Encoding.UTF8);
                t.Namespaces = true;
                XDocument xd = XDocument.Load("http://channel9.msdn.com/Shows/This+Week+On+Channel+9/RSS");
                if (xd != null)
                    xd.WriteTo(t);
                t.Flush();
                t.Close();
            }
            catch (Exception ex)
            {
                MyLog.WriteErr<AdminTasks>("Error in AdminTasks::WriteTWC9File()", ex);
                throw ex;
            }
            MyLog.Write<AdminTasks>("AdminTasks::WriteTWC9File()", "Method Call End");

        }

        public static void WritePBDeskRssFile()
        {
            MyLog.Write<AdminTasks>("AdminTasks::WritePBDeskRssFile()", "Method Call Start");
            try
            {
                string fileName =  MyUmb.CacheFilesLoc + "PBDeskRss.xml";
                SyndicationFeed feed = FeedHelper.GetPBDeskComRss(100);               
                using(var w = XmlWriter.Create(File.Create(fileName)))
                {
                    feed.SaveAsRss20(w);
                    w.Flush();
                    w.Close();
                }

            }
            catch (Exception ex)
            {
                MyLog.WriteErr<AdminTasks>("Error in AdminTasks::WritePBDeskRssFile()", ex);
                throw ex;
            }
            MyLog.Write<AdminTasks>("AdminTasks::WritePBDeskRssFile()", "Method Call End");

        }

        public static void GenerateNewsFeedsCache()
        {
            MyLog.Write<AdminTasks>("AdminTasks::GenerateNewsFeedsCache()", "Method Call Start");
            string[] entries = new string[] {"technews","technews-cs","technews-vb","technews-dotnet",
                                              "technews-aspnet","technews-aspnetmvc","technews-umbraco","technews-silverlight",
                                              "technews-vstudio","technews-msdn"};
            foreach (string s in entries)
            {
                UpdateNewsFeedCache(s);
            }          
            MyLog.Write<AdminTasks>("AdminTasks::GenerateNewsFeedsCache()", "Method Call End");
        }

        private static void UpdateNewsFeedCache(string entry)
        {
            MyLog.Write<AdminTasks>("AdminTasks::UpdateNewsFeedCache", "Method Call start.");
            RssEntry  rssEntry =  FeedHelper.GetRssEntry("technews");
            if (rssEntry != null)
            {
                MyLog.Write<AdminTasks>("AdminTasks::UpdateNewsFeedCache", "Method Call for " + entry);
                SyndicationFeed feed = null;
                try
                {
                    var items = from url in rssEntry.FeedUrls
                                from xr in CustomXmlReader.Create(url).Use()
                                let feed1 = SyndicationFeed.Load(xr)
                                from i in feed1.Items.OrderByDescending(dt => dt.PublishDate)
                                select i;

                    feed = new SyndicationFeed(rssEntry.Title, rssEntry.Desc, new Uri(rssEntry.Link), items.Distinct().OrderByDescending(dt => dt.PublishDate));
                    feed.ImageUrl = new Uri(rssEntry.ImageUrl);
                    feed.Generator = "PBDesk.com Feed Aggrigator";
                    feed.LastUpdatedTime = new DateTimeOffset(DateTime.Now);
                }
                catch(Exception ex)
                {
                    MyLog.WriteErr<AdminTasks>("Error in AdminTasks::UpdateNewsFeedCache() while generating feed object", ex);
                    throw ex;

                }
                WriteFeedToFile(rssEntry.CacheFile, feed);
            
            }
            MyLog.Write<AdminTasks>("AdminTasks::UpdateNewsFeedCache", "Method Call end.");
           
        }

        private static void WriteFeedToFile(string fileName, SyndicationFeed feed)
        {
            if (feed != null && fileName.IsNotNullAndNotEmpty())
            {
                try
                {
                    string fullPath = MyUmb.CacheFilesLoc + fileName;
                    XmlTextWriter t = new XmlTextWriter(fullPath, Encoding.UTF8);
                    t.Namespaces = true;
                    feed.SaveAsRss20(t);
                    t.Flush();
                    t.Close();
                }
                catch (Exception ex)
                {
                    MyLog.WriteErr<AdminTasks>("Error in AdminTasks::WriteFeedToFile() while writing feed to file", ex);
                    throw ex;
                }
            }
            else
            {
                MyLog.Write<AdminTasks>("AdminTasks::UpdateNewsFeedCache", "Feed cache not generated as feed object is null or not a valid filename.");
            }
        }
    }
}
